package com.sy.simpleegg.upgrade;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;

import com.sy.simpleegg.config.Config;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

public class UpgradeManager {

    public static Context context;

    public static final String VERSIONINFO = "VERSION_INFO";

    public static boolean receiveReboot = false;

    public static boolean isManualCheckVersion = false;

    private static int txtFailCount = 0;

    public void init(Context context){
        UpgradeManager.context = context;
    }

    public void checkUpgrade(){

    }

    public static void saveAppConfigAddress(String verUrl){
        if (!TextUtils.isEmpty(verUrl)){
            writeToLocal(verUrl);
            checkVersion(verUrl);
        }else{
            if (mUpgradeListener != null && receiveReboot){
                mUpgradeListener.rebootAndroid();
            }
        }
    }

    /**
     * 本地保存APP版本配置url
     * @param verUrl
     */
    private static void writeToLocal(String verUrl){
        if (TextUtils.isEmpty(verUrl)){
            return;
        }
        String content = "{jsonUrl:" + "\"" + verUrl + "\"}";
        Log.d("MainActivity", "content = " + content);
        File file = new File(Config.INSTANCE.getDEF_UPGRADE_PATH() ,"update.json");
        if (!file.exists()){
            File dir = new File(file.getParent());
            dir.mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(file);
            outStream.write(content.getBytes());
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检测版本
     * @param verUrl
     */
    private static void checkVersion(String verUrl){
//        AppUpgradeAction appUpgradeAction = new AppUpgradeAction(MainActivity.getMainActivity());
//        appUpgradeAction.updateJson(getAppVersion(), url);
        updateJson(getVersionName(context), verUrl);
    }

    /**
     * [获取应用程序版本名称信息]
     * @param context
     * @return 当前应用的版本名称
     */
    private static synchronized String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新appInfo.json
     * @param curVersion
     * @param url
     */
    private static void updateJson(final String curVersion, final String url){
        final String savePath = Config.INSTANCE.getDEF_UPGRADE_PATH();
        final String name = "appInfo.json";

        File saveFile = new File(savePath, name);
        if (saveFile.exists()){
            saveFile.delete();
        }

        Thread thread = new Thread(){
            @Override
            public void run() {
                FileDownloader.download(savePath, name, url, new FileDownloader.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(String loadUrl, String filePath) {
                        Log.d("AppUpgrade", "下载更新文本成功：" + filePath);
                        checkVersionSelf(curVersion);
                    }

                    @Override
                    public void onDownloading(long progress, long total) {
//                        Log.d("AppUpgrade", "下载文本进度-" + (int) (((float)progress / (float)total) * 100));
//                        progressDialog.setProgress((int) (((float)progress / (float)total) * 100));
                    }

                    @Override
                    public void onDownloadFailed(String errorInfo) {
                        Log.d("AppUpgrade", "下载文本失败：" + errorInfo);
                        txtFailCount ++;

                        if (txtFailCount > 2){
                            checkReboot(false);
                        }else{
                            Timer timer = new Timer();
                            timer.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    updateJson(curVersion, url);
                                }
                            }, 1500);
                        }

                    }
                });
            }
        };
        thread.start();
    }

    /**
     * 对比版本
     * @param curVersion
     */
    private static void checkVersionSelf(String curVersion){
        String appInfo = readTxtFile(Config.INSTANCE.getDEF_UPGRADE_PATH() + "/appInfo.json");
        Log.d("AppUpgradeAction", "更新json = " + appInfo);
        if (appInfo.isEmpty()){
            checkReboot(false);
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(appInfo.substring(appInfo.indexOf("{"), appInfo.indexOf("}") + 1));
            String version = jsonObject.getString("VersionCode");

            int isUpdate = compareVersion(curVersion, version);

            if (isUpdate == -1){
                // 需要更新
                checkReboot(true);
//                updateApp(url, "ZIAI.apk", version);
            }else{
                // 不需要更新，直接打开主app
                checkReboot(false);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            checkReboot(false);
        }
    }

    /**
     * 读取文本
     * @param strFilePath 文本目录
     * @return String
     */
    private static String readTxtFile(String strFilePath)
    {
        String path = strFilePath;
        String content = ""; //文件内容字符串
        //打开文件
        File file = new File(path);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory())
        {
            Log.d("TestFile", "The File doesn't not exist.");
        }
        else
        {
            try {
                InputStream instream = new FileInputStream(file);
                if (instream != null)
                {
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    //分行读取
                    while (( line = buffreader.readLine()) != null) {
                        content += line;
                    }
                    instream.close();
                }
            }
            catch (java.io.FileNotFoundException e)
            {
                Log.d("TestFile", "The File doesn't not exist.");
            }
            catch (IOException e)
            {
                Log.d("TestFile", e.getMessage());
            }
        }
        return content;
    }

    /**
     * 版本号比较
     * @param version1 当前版本
     * @param version2 新版本
     * @return 0代表相等，1代表version1大于version2，-1代表version1小于version2
     */
    private static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        Log.d("compareVersion", "version1Array=="+version1Array.length);
        Log.d("compareVersion", "version2Array=="+version2Array.length);
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        Log.d("HomePageActivity", "verTag2=2222="+version1Array[index]);
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index ++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    /**
     * 检测是否需要重启更新
     * @param versionResult 版本对比结果
     */
    private static void checkReboot(boolean versionResult){
        // 保存更新状态
        if (versionResult && receiveReboot){
            saveRebootUpdata(true);
        }
        //手动检测版本更新
        updateVersionInfo(versionResult);

        if(receiveReboot){
            receiveReboot = false;
            if (mUpgradeListener != null){
                mUpgradeListener.rebootAndroid();
            }
        }
    }

    /**
     * 保存重启状态
     * @param isReboot 重启状态
     */
    private static void saveRebootUpdata(boolean isReboot){
        Log.d("writeRebootState", "state = " + isReboot);
        File rebootFile = new File(Config.INSTANCE.getDEF_UPGRADE_PATH() , "reboot.json");
        if (rebootFile.exists()){
            Log.d("writeRebootState", "rebootFile.exists()");
            rebootFile.delete();
            try {
                rebootFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("writeRebootState", "createNewFile-err:" + e.getMessage());
            }
            String content;
            if (isReboot){
                content = "{\"reboot\":" + "\"" + 1 + "\"}";
            }else{
                content = "{\"reboot\":" + "\"" + 0 + "\"}";
            }

            FileOutputStream outStream = null;
            try {
                outStream = new FileOutputStream(rebootFile);
                outStream.write(content.getBytes());
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("writeRebootState", "outStream-err:" + e.getMessage());
            }
        }else{
            Log.d("writeRebootState", "!rebootFile.exists()");
            File dir = new File(rebootFile.getParent());
            dir.mkdirs();
            try {
                rebootFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("writeRebootState", "createNewFile-err:" + e.getMessage());
            }

            String content;
            if (isReboot){
                content = "{\"reboot\":" + "\"" + 1 + "\"}";
            }else{
                content = "{\"reboot\":" + "\"" + 0 + "\"}";
            }

            FileOutputStream outStream = null;
            try {
                outStream = new FileOutputStream(rebootFile);
                outStream.write(content.getBytes());
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("writeRebootState", "outStream-err:" + e.getMessage());
            }
        }
    }

    public static UpgradeListener mUpgradeListener;

    public interface UpgradeListener{
        void rebootAndroid();
        void sendVersionInfo(boolean hasUpgrade);
    }

    public void setOnUpgradeListener(UpgradeListener upgradeListener){
        this.mUpgradeListener = upgradeListener;
    }

    /**
     * 版本检测界面版本信息
     * @param isUpgrade 是否有新版本
     */
    private static void updateVersionInfo(boolean isUpgrade){
        if (isManualCheckVersion){
            isManualCheckVersion = false;
            if (mUpgradeListener != null){
                mUpgradeListener.sendVersionInfo(isUpgrade);
            }
        }
    }
}
